package com.zxyankh.leetcode.question.chinese;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 给定一个无重复元素的数组 candidates 和一个目标数 target ，找出 candidates 中所有可以使数字和为 target 的组合。
 * <p>
 * candidates 中的数字可以无限制重复被选取。
 * <p>
 * 说明：
 * <p>
 * 所有数字（包括 target）都是正整数。
 * 解集不能包含重复的组合。 
 * 示例 1:
 * <p>
 * 输入: candidates = [2,3,6,7], target = 7,
 * 所求解集为:
 * [
 * [7],
 * [2,2,3]
 * ]
 * 示例 2:
 * <p>
 * 输入: candidates = [2,3,5], target = 8,
 * 所求解集为:
 * [
 *   [2,2,2,2],
 *   [2,3,3],
 *   [3,5]
 * ]
 *
 * @author zxyAnkh
 */
public class No39 {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < candidates.length; i++) {
            int n = target - candidates[i];
            if (n == 0) {
                result.add(Collections.singletonList(candidates[i]));
            } else if (n > 0) {
                List<Integer> list = new ArrayList<>();
                list.add(candidates[i]);
                combinationSum(result, list, i, candidates, n);
            }
        }
        return result;
    }

    private void combinationSum(List<List<Integer>> result, List<Integer> list, int i, int[] candidates, int target) {
        for (int j = i; j < candidates.length; j++) {
            int n = target - candidates[j];
            if (n == 0) {
                List<Integer> l = new ArrayList<>(list);
                l.add(candidates[j]);
                result.add(l);
            } else if (n > 0) {
                List<Integer> l = new ArrayList<>(list);
                l.add(candidates[j]);
                combinationSum(result, l, j, candidates, n);
            }
        }
    }

}
